package org.vectrics.company.dataweb;

import javax.servlet.http.HttpServletRequest;

import org.vectrics.common.dom.MarshalUtils;
import org.vectrics.company.Company;
import org.vectrics.dataweb.WebServiceAction;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.VectricsException;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;



public class FindCompanyAction extends WebServiceAction {
	static private transient Logger log = Logger.getLogger(FindCompanyAction.class);
	static private String COMMAND_NOT_FOUND = "Command not found or not given: ";	
	
	public FindCompanyAction() {
		super();
	}

	public void getData(Request request, String command, Element requestData, 
			Element dataElement) {
		log.debug("getData() - retrieveing data for company");
		NodeList nodeList = requestData.getElementsByTagName("companyList");
		if (nodeList.getLength() > 0) {
			Element companyListElement = (Element)nodeList.item(0);
			findCompanies(companyListElement, dataElement);
		}
		else {
			findCompanies(requestData, dataElement);
		}
		
	}

	private void findCompanies(Element companyListElement, Element dataElement) {
		NodeList nodeList = companyListElement.getElementsByTagName("company");
		if (log.isDebugEnabled()) {
			log.debug("getData() - requested number of companies = " + nodeList.getLength());
		}
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element companyElement = (Element)nodeList.item(i);
			Long companyId = new Long(companyElement.getAttribute("id"));
			if (log.isDebugEnabled()) {
				log.debug("getData() - found id to lookup, id = " + companyId);
			}
			Company company = CoreServiceLocator.getCompanyService().findCompany(companyId);
			MarshalUtils marshaller = MarshalUtils.getInstance();
			marshaller.objectToElement(dataElement, company, "company");
		}
	}
	

	
}

